<?php
namespace App\Models;

use App\Config\Database;
use PDO;
use PDOException;

/**
 * 好友请求模型
 * @package App\Models
 * @description:
 * 1. 发送好友请求
 * 2. 处理好友请求（接受/拒绝）
 * 3. 获取好友请求列表
 * 4. 检查是否有未处理的请求
 */
class FriendRequest {
    private $conn;
    private $table = 'friend_requests';

    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection();
    }

    /**
     * 发送好友请求
     * @param int $fromUserId 申请人ID
     * @param int $toUserId 被申请人ID
     * @param string $message 附言
     * @return bool
     */
    public function sendRequest($fromUserId, $toUserId, $message = '') {
        try {
            $query = "INSERT INTO " . $this->table . " 
                      (from_user_id, to_user_id, status, message) 
                      VALUES (:from_user_id, :to_user_id, 0, :message)";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':from_user_id', $fromUserId);
            $stmt->bindParam(':to_user_id', $toUserId);
            $stmt->bindParam(':message', $message);
            
            return $stmt->execute();
        } catch (PDOException $e) {
            // 唯一键冲突表示已有请求
            if ($e->getCode() == 23000) {
                return $this->updateRequestStatus($fromUserId, $toUserId, 0);
            }
            error_log("Send friend request error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 更新好友请求状态
     * @param int $fromUserId 申请人ID
     * @param int $toUserId 被申请人ID
     * @param int $status 状态：0-待处理，1-已接受，2-已拒绝，3-已过期
     * @return bool
     */
    public function updateRequestStatus($fromUserId, $toUserId, $status) {
        try {
            $query = "UPDATE " . $this->table . " 
                      SET status = :status, updated_at = CURRENT_TIMESTAMP
                      WHERE from_user_id = :from_user_id AND to_user_id = :to_user_id";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':from_user_id', $fromUserId);
            $stmt->bindParam(':to_user_id', $toUserId);
            
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Update request status error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取好友请求列表
     * @param int $userId 用户ID
     * @param int $type 1-我收到的请求，2-我发送的请求
     * @param int $status 请求状态（null表示所有状态）
     * @return array
     */
    public function getRequests($userId, $type = 1, $status = null) {
        try {
            $conditions = [];
            $params = [];
            
            if ($type == 1) {
                // 我收到的请求
                $conditions[] = "to_user_id = :user_id";
                $params[':user_id'] = $userId;
            } else {
                // 我发送的请求
                $conditions[] = "from_user_id = :user_id";
                $params[':user_id'] = $userId;
            }
            
            if ($status !== null) {
                $conditions[] = "status = :status";
                $params[':status'] = $status;
            }
            
            $whereClause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";
            $orderBy = "ORDER BY created_at DESC";
            
            $query = "SELECT fr.*, u.user_id, u.username, u.avatar_url 
                      FROM " . $this->table . " fr
                      JOIN users u ON " . ($type == 1 ? "fr.from_user_id" : "fr.to_user_id") . " = u.id
                      " . $whereClause . " " . $orderBy;
            
            $stmt = $this->conn->prepare($query);
            
            // 绑定参数
            foreach ($params as $key => $value) {
                $stmt->bindValue($key, $value, PDO::PARAM_INT);
            }
            
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Get friend requests error: " . $e->getMessage());
            return [];
        }
    }

    /**
     * 检查是否有未处理的好友请求
     * @param int $userId 用户ID
     * @return bool
     */
    public function hasPendingRequests($userId) {
        try {
            $query = "SELECT COUNT(*) as count 
                      FROM " . $this->table . " 
                      WHERE to_user_id = :user_id AND status = 0";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':user_id', $userId);
            $stmt->execute();
            
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return $result['count'] > 0;
        } catch (PDOException $e) {
            error_log("Check pending requests error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 处理好友请求（接受/拒绝）
     * @param int $requestId 请求ID
     * @param int $action 1-接受，2-拒绝
     * @return bool
     */
    public function handleRequest($requestId, $action) {
        try {
            $this->conn->beginTransaction();
            
            // 获取请求信息
            $query1 = "SELECT * FROM " . $this->table . " WHERE id = :id FOR UPDATE";
            $stmt1 = $this->conn->prepare($query1);
            $stmt1->bindParam(':id', $requestId);
            $stmt1->execute();
            $request = $stmt1->fetch(PDO::FETCH_ASSOC);
            
            if (!$request) {
                $this->conn->rollBack();
                return false;
            }
            
            // 更新请求状态
            $status = ($action == 1) ? 1 : 2;
            $query2 = "UPDATE " . $this->table . " 
                      SET status = :status 
                      WHERE id = :id";
            $stmt2 = $this->conn->prepare($query2);
            $stmt2->bindParam(':status', $status);
            $stmt2->bindParam(':id', $requestId);
            $stmt2->execute();
            
            // 如果是接受，添加好友关系
            if ($action == 1) {
                $friendModel = new Friend();
                $friendModel->addFriend($request['from_user_id'], $request['to_user_id']);
            }
            
            $this->conn->commit();
            return true;
        } catch (PDOException $e) {
            $this->conn->rollBack();
            error_log("Handle friend request error: " . $e->getMessage());
            return false;
        }
    }
}